package com.weichen.xd;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.weichen.xd.data.AllWeather;
import com.weichen.xd.data.City;
import com.weichen.xd.data.DailyForecast;
import com.weichen.xd.data.HeWeather5;
import com.weichen.xd.utils.CPResourceUtil;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CityWeatherActivity extends AppCompatActivity {

    public static final String E = "e";

    public static void startActivity(Activity activity, City city) {

        Intent intent = new Intent(activity, CityWeatherActivity.class);
        intent.putExtra(E, city);
        activity.startActivity(intent);
    }

    @BindView(R.id.tv_city_name)
    TextView tvCityName;
    @BindView(R.id.tv_top_tem)
    TextView tvTopTem;
    @BindView(R.id.iv_top_weather_ic)
    ImageView ivTopWeatherIc;
    @BindView(R.id.tv_top_weather_txt)
    TextView tvTopWeatherTxt;
    @BindView(R.id.tv_top_weather_tem_range)
    TextView tvTopWeatherTemRange;
    @BindView(R.id.tv_top_week)
    TextView tvTopWeek;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.rv_hours_weather)
    RecyclerView rvHoursWeather;
    @BindView(R.id.rv_date_weather)
    RecyclerView rvDateWeather;
    @BindView(R.id.iv_detail_weather_ic)
    ImageView ivDetailWeatherIc;
    @BindView(R.id.tv_detail_tem_txt)
    TextView tvDetailTemTxt;
    @BindView(R.id.tv_detail_fl)
    TextView tvDetailFl;
    @BindView(R.id.tv_detail_hum)
    TextView tvDetailHum;
    @BindView(R.id.tv_detail_spd_dir)
    TextView tvDetailSpdDir;
    @BindView(R.id.tv_detail_sr)
    TextView tvDetailSr;
    @BindView(R.id.tv_detail_ss)
    TextView tvDetailSs;
    @BindView(R.id.tv_detail_qlty)
    TextView tvDetailQlty;
    @BindView(R.id.tv_detail_pm25)
    TextView tvDetailPm25;


    private DateWeatherAdapter mDateWeatherAdapter;
    private HourlyWeatherAdapter mHourlyWeatherAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_weather);
        ButterKnife.bind(this);

        mDateWeatherAdapter = new DateWeatherAdapter();
        mHourlyWeatherAdapter = new HourlyWeatherAdapter();

        rvDateWeather.setAdapter(mDateWeatherAdapter);
        rvDateWeather.setNestedScrollingEnabled(false);
        rvHoursWeather.setAdapter(mHourlyWeatherAdapter);
        rvHoursWeather.setNestedScrollingEnabled(false);


        City city = getIntent().getParcelableExtra(E);
        setRequest(city.getCity());
    }

    private void setRequest(final String city) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(String.format("https://free-api.heweather.com/v5/weather?city=%s&key=02bd641880f146a4b66f137e683e0189",
                                city))
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    String s = response.body().string();
                    final AllWeather weather = new Gson().fromJson(s, AllWeather.class);

                    if (!isFinishing()) {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshUI(weather.getHeWeather5().get(0));
                            }
                        });
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void refreshUI(HeWeather5 weather) {

        if ("ok".equals(weather.getStatus())) {

            ivTopWeatherIc.setImageResource(CPResourceUtil.getDrawableId(
                    this, "ic_code_" + weather.getNow().getCond().getCode()));


            ivDetailWeatherIc.setImageResource(CPResourceUtil.getDrawableId(
                    this, "ic_code_" + weather.getNow().getCond().getCode()));
            tvCityName.setText(weather.getBasic().getCity());
            tvTopTem.setText(weather.getNow().getTmp());
            tvTopWeatherTxt.setText(weather.getNow().getCond().getTxt());

            DailyForecast dailyForecast = weather.getDailyForecast().get(0);
            tvTopWeatherTemRange.setText(getString(R.string.format_tmp_max_min,
                    dailyForecast.getTmp().getMin(), dailyForecast.getTmp().getMax()));


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            try {
                Date date = sdf.parse(dailyForecast.getDate());
                tvTopWeek.setText(getWeekOfDate(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            mDateWeatherAdapter.setDailyForecast(weather.getDailyForecast());
            mHourlyWeatherAdapter.setHourlyForecast(weather.getHourlyForecast());

            tvDetailTemTxt.setText(weather.getNow().getCond().getTxt());
            tvDetailFl.setText(getString(R.string.format_tmp, weather.getNow().getFl()));
            tvDetailHum.setText(weather.getNow().getHum() + "%");
            tvDetailSpdDir.setText(
                    weather.getNow().getWind().getDir() + weather.getNow().getWind().getSc() + "级");

            tvDetailSr.setText(dailyForecast.getAstro().getSr());
            tvDetailSs.setText(dailyForecast.getAstro().getSs());
            if (weather.getAqi() != null) {

                tvDetailPm25.setText(weather.getAqi().getCity().getPm25());
                tvDetailQlty.setText(getString(R.string.format_aqi, weather.getAqi().getCity().getQlty(),
                        weather.getAqi().getCity().getAqi()));
            }

        }
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

}
